﻿#ifndef W_TCP_SERVER_H
#define W_TCP_SERVER_H

#include <cstring>
#include <map>
#include <random>
#include <chrono>
#include <mutex>
#include <shared_mutex>

#include "common.h"
#include "singleton.h"
#include "NedAllocatedObject.h"
#include "networkframemanager.h"

class WTCPServer;

// 客户端信息结构
class TCPClientInfo : public NedAllocatedObject
{
public:
    TCPClientInfo(wxString cName,
               WTCPServer *cServer);
    ~TCPClientInfo();

    inline void RemoveDataFromMemoryBuffer(size_t pos, size_t len)
    {
        if (pos < 0 || pos >= buffer.GetDataLen() || len == 0)
            return;

        size_t remainingBytes = buffer.GetDataLen() - pos - len;
        if (remainingBytes > 0) {
            void* dest = static_cast<char*>(buffer.GetData()) + pos;
            const void* src = static_cast<char*>(buffer.GetData()) + pos + len;
            memmove(dest, src, remainingBytes);
        }

        buffer.SetDataLen(buffer.GetDataLen() - len); // 调整缓冲区大小
    }

    void deleteMe(void);

    bool SendData(int msgtype,const void* data,size_t len);
    bool Send(const void* data, size_t len);

    wxString clientName;
    wxSocketBase* socket;
    wxDateTime lastActiveTime;
    wxMemoryBuffer buffer;

    tagMsgHearder mMsgHearder;
    bool isProcessMsgHearder;
    int errorCount;
};

class WTCPServer : public wxEvtHandler
{
public:
    WTCPServer(wxString ip="127.0.0.1",
                  int port=10051);
    ~WTCPServer();

    /// 打开服务器
    bool Open(void);
    /// 关闭服务器
    void Close(void);
    /// 设置服务器IP和端口
    bool setServerParams(wxString ip,int port);
    /// 得到当前系统操控客户端
    inline const TCPClientInfo* getOperClient(void) { return m_curOperClient; }
    /// 设置当前系统操控客户端
    inline void setOperClient(TCPClientInfo* client) { m_curOperClient = client; }
    /// 设置发送缓冲区大小
    inline void setSendBufferSize(uint32_t size) { m_sendbufsize = size; }
    /// 得到服务器IP
    inline wxString getServerIP(void) { return m_ServerIP; }
    /// 得到服务器端口
    inline int getServerPort(void) { return m_ServerPort; }
    /// 设置网络处理框架
    inline void setNetworkFrameManager(NetworkFrameManager *nfm) { m_NetworkFrameManager = nfm; }
    /// 得到网络处理框架
    inline NetworkFrameManager* getNetworkFrameManager(void) { return m_NetworkFrameManager; }
    /// 发送消息
    bool SendData(int msgtype,const void* data,size_t len,const char* clientid=NULL);
    bool SendDataOther(int msgtype,const void* data,size_t len,const char* clientid);

private:
    void OnServerEvent(wxSocketEvent& event);
    void OnClientConnected(wxSocketBase* serverSock);
    void OnSocketData(wxSocketBase* clientSock);
    void OnClientDisconnected(wxSocketBase* clientSock);
    void OnClientClosedEvent(wxThreadEvent& event);
    void OnHeartTimeOutTimer(wxTimerEvent& event);

private:
    TCPClientInfo* FindClientId(wxSocketBase* sock);
    TCPClientInfo* FindClientName(wxString clientName);

private:
    wxString m_ServerIP;                               /**< 服务器IP */
    int m_ServerPort;                                  /**< 服务器端口 */
    wxSocketServer* m_tcpserver;                       /**< tcp服务器管理 */
    std::map<wxSocketBase*, TCPClientInfo*> m_clients;    /**< 管理所有在线的tcp客户端 */
    mutable std::shared_mutex m_clientsMutex;                  /**< 保护所有的客户端 */
    wxTimer *m_HeartTimeOutTimer;                      /**< 心跳定时器 */
    NetworkFrameManager *m_NetworkFrameManager;        /**< 网络处理框架 */
    uint32_t m_sendbufsize;                            /**< 发送缓冲区大小 */
    TCPClientInfo* m_curOperClient;                       /**< 当前操控系统的客户端 */
};

#endif
